package com.init.iblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.init.iblog.domain.entity.LoginUser;
import com.init.iblog.domain.entity.User;
import com.init.iblog.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 实现UserDetailsService接口，重写loadUserByUsername
 * 重写loadUserByUsername方法默认在内容中进行验证，重写方法，使其去数据库中查询数据进行验证
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired(required = false)
    private UserMapper userMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getName,username);
        User user = userMapper.selectOne(lambdaQueryWrapper);

        //判断是否查到用户，没有查到用户抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        //返回用户信息
        //TODO  查询权限信息封装

        //LoginUser实体类实现UserDetails
        return new LoginUser(user);
    }
}
